package com.wudizaba.microservicesdemosystem.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;


/**
 * Excel工具类
 * @author wudizaba
 *
 */
public class ExcelUtils<T> {



    //导出+下载
    public void exportAndDownload(HttpServletResponse response, List<T> list, String fileName, Class<T> clazz, String sheetName ) throws IOException {
        setExcelResponseProp(response, fileName);
        EasyExcel.write(response.getOutputStream())
                .head(clazz)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet(sheetName)
                .doWrite(list);
    }

    private void setExcelResponseProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8").replaceAll("\regex, replacement+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8" + fileName + ".xlsx");
    }

}
